import { Component, OnInit, ViewChild } from '@angular/core';
import { STComponent, STColumn, STRequestOptions } from '@delon/abc/st';
import { NzModalService } from 'ng-zorro-antd/modal';
import { SystemService } from '../../services/system.service';

@Component({
  selector: 'app-goods-name-config',
  templateUrl: './goods-name-config.component.html',
  styleUrls: ['./goods-name-config.component.less']
})
export class GoodsNameConfigComponent implements OnInit {
  @ViewChild('configTypeModal', { static: true })
  configTypeModal: any;
  @ViewChild('configTypeItemModal', { static: true })
  configTypeItemModal: any;
  @ViewChild('st', { static: true })
  st!: STComponent;
  typeList: any[] = [];
  selectedType: any = null;
  parentId = null;

  columns: STColumn[] = [
    { title: '货物名称', index: 'name' },
    { title: '更新时间', index: 'modifyTime' },
    {
      title: '操作',
      className: 'text-center',
      buttons: [
        {
          text: '编辑',
          acl: { ability: ['SYSTEM-GOODS-NAME-CONFIG-edit'] },
          click: item => this.typeItemAction(item)
        },
        {
          text: '上移',
          acl: { ability: ['SYSTEM-GOODS-NAME-CONFIG-sort'] },
          click: item => this.sortTypeItem(item, 3)
        },
        {
          text: '下移',
          acl: { ability: ['SYSTEM-GOODS-NAME-CONFIG-sort'] },
          click: item => this.sortTypeItem(item, 4)
        },
        {
          text: '删除',
          acl: { ability: ['SYSTEM-GOODS-NAME-CONFIG-delete'] },
          click: item => this.removeTypeItem(item)
        }
      ]
    }
  ];

  configTypeName = '';
  configTypeItemName = '';
  searchName = '';
  constructor(public service: SystemService, private nzModalService: NzModalService) {}

  ngOnInit(): void {
    this.getTypeList();
  }

  beforeReq = (requestOptions: STRequestOptions) => {
    Object.assign(requestOptions.body, {
      configId: this.selectedType?.id
    });
    if (this.searchName) {
      Object.assign(requestOptions.body, {
        name: this.searchName
      });
    }
    return requestOptions;
  };

  keydownEvent(event: any) {
    if (event.keyCode === 13) {
      this.st.load(1);
    }
  }

  getTypeList() {
    this.service.request(this.service.$api_get_config_tree, { configFullKey: 'goods.name.config' }).subscribe((res: Array<any>) => {
      if (res?.length > 0) {
        const typeData = res
          .find(config => config.configFullKey === 'goods.name.config')
          ?.children.find((type: any) => type.configFullKey === 'goods.name.config.type');
        if (typeData) {
          this.typeList = typeData.children;
          this.parentId = typeData.id;
          this.selectedType = typeData.children[0];
        }
      }
    });
  }

  selectedTypeAction(item: any) {
    this.selectedType = item;
    this.st.load(1);
  }

  /**
   * 货物类型操作
   * @param item
   */
  typeAction(item?: any) {
    this.configTypeName = item?.name || '';
    this.nzModalService.create({
      nzTitle: item ? '编辑' : '新增',
      nzContent: this.configTypeModal,
      nzOnOk: () => {
        if (!this.configTypeName) {
          this.service.msgSrv.warning('请填写货物类型');
          return false;
        }
        if (item) {
          this.service.request(this.service.$api_update_config, { ...item, name: this.configTypeName }).subscribe(res => {
            if (res) {
              this.service.msgSrv.success('更新货物类型成功');
              this.getTypeList();
            }
          });
        } else {
          this.service.request(this.service.$api_add_config, { name: this.configTypeName, parentId: this.parentId }).subscribe(res => {
            if (res) {
              this.service.msgSrv.success('新增货物类型成功');
              this.getTypeList();
            }
          });
        }
        return true;
      }
    });
  }

  /**
   * 货物名称操作
   * @param item
   */
  typeItemAction(item?: any) {
    this.configTypeItemName = item?.name || '';
    this.nzModalService.create({
      nzTitle: item ? '编辑' : '新增',
      nzContent: this.configTypeItemModal,
      nzOnOk: () => {
        if (!this.configTypeItemName) {
          this.service.msgSrv.warning('请填写货物名称');
          return false;
        }
        if (item) {
          this.service.request(this.service.$api_update_config_item, { ...item, name: this.configTypeItemName }).subscribe(res => {
            if (res) {
              this.service.msgSrv.success('更新货物名称成功');
              this.st.load(1);
            }
          });
        } else {
          this.service
            .request(this.service.$api_add_config_item, {
              name: this.configTypeItemName,
              configId: this.selectedType.id
            })
            .subscribe(res => {
              if (res) {
                this.service.msgSrv.success('新增货物名称成功');
                this.st.load(1);
              }
            });
        }
        return true;
      }
    });
  }

  /**
   * 删除货物类型
   * @param item
   */
  removeType(item: any) {
    this.nzModalService.warning({
      nzTitle: '确定删除该货物类型吗？',
      nzContent: '分类下含有内容则无法删除，请确认',
      nzOnOk: () => {
        this.service.request(this.service.$api_remove_config, [item.id]).subscribe(res => {
          if (res) {
            this.getTypeList();
            this.service.msgSrv.success('删除货物类型成功');
          }
        });
      }
    });
  }

  /**
   * 删除货物名称
   * @param item
   */
  removeTypeItem(item: any) {
    this.nzModalService.warning({
      nzTitle: '确定删除该货物名称吗？',
      nzContent: '删除后不可恢复，谨慎操作',
      nzOnOk: () => {
        this.service.request(this.service.$api_remove_config_item, [item.id]).subscribe(res => {
          if (res) {
            this.service.msgSrv.success('删除货物名称成功');
            this.st.load(1);
          }
        });
      }
    });
  }

  /**
   * 修改类型排序
   * @param item
   * @param sortMode
   */
  sortType(item: any, sortMode: 1 | 2 | 3 | 4) {
    this.service.request(this.service.$api_update_config_sort, { id: item.id, sortMode }).subscribe(res => {
      if (res) {
        this.service.msgSrv.success('更新排序成功');
        this.getTypeList();
      } else {
        this.service.msgSrv.warning('更新排序失败');
      }
    });
  }

  /**
   * 修改类型详情排序
   * @param item
   * @param sortMode
   */
  sortTypeItem(item: any, sortMode: 1 | 2 | 3 | 4) {
    this.service.request(this.service.$api_update_config_item_sort, { id: item.id, sortMode }).subscribe(res => {
      if (res) {
        this.service.msgSrv.success('更新排序成功');
        this.st.load(1);
      } else {
        this.service.msgSrv.warning('更新排序失败');
      }
    });
  }
}
